package com.ruoyi.pv.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.doudou.core.thread.ExecutorUtil;
import com.ruoyi.cert.domain.Cert;
import com.ruoyi.cert.service.ICertService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.aliyun.MySms;
import com.ruoyi.pv.domain.PvClassScore;
import com.ruoyi.pv.domain.PvStudentRecord;
import com.ruoyi.pv.mapper.PvClassScoreMapper;
import com.ruoyi.pv.service.IPvStudentRecordService;
import com.ruoyi.pv.service.IPvUserInfoService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pv.mapper.PvTrainingClassMapper;
import com.ruoyi.pv.domain.PvTrainingClass;
import com.ruoyi.pv.service.IPvTrainingClassService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 培训班管理Service业务层处理
 *
 * @author zzx
 * @date 2023-03-12
 */
@Service
@Slf4j
public class PvTrainingClassServiceImpl implements IPvTrainingClassService {

    @Autowired private PvTrainingClassMapper pvTrainingClassMapper;
    @Autowired private PvClassScoreMapper classScoreMapper;
    @Autowired private ISysUserService userService;
    @Autowired private IPvUserInfoService infoService;
    @Autowired private ICertService certService;
    @Autowired private IPvStudentRecordService pvStudentRecordService;
//    @Autowired private MySms sms;



    /**
     * 查询培训班管理
     *
     * @param id 培训班管理主键
     * @return 培训班管理
     */
    @Override
    public PvTrainingClass selectPvTrainingClassById(Long id) {
        return pvTrainingClassMapper.selectPvTrainingClassById(id);
    }

    /**
     * 查询培训班管理列表
     *
     * @param pvTrainingClass 培训班管理
     * @return 培训班管理
     */
    @Override
    public List<PvTrainingClass> selectPvTrainingClassList(PvTrainingClass pvTrainingClass) {
        return pvTrainingClassMapper.selectPvTrainingClassList(pvTrainingClass);
    }

    /**
     * 新增培训班管理
     *
     * @param pvTrainingClass 培训班管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPvTrainingClass(PvTrainingClass pvTrainingClass) {
        pvTrainingClass.setCreateTime(DateUtils.getNowDate());
        int i = pvTrainingClassMapper.insertPvTrainingClass(pvTrainingClass);
        classScoreMapper.insertPvClassScore(PvClassScore.builder().id(pvTrainingClass.getId()).build());
        return i;
    }

    /**
     * 修改培训班管理
     * <p>
     *   TODO 【2023-07-07 更新需求】
     *   培训班-修改班级状态改为毕业（dict:2）的时候，
     *   多提示一下确认全局查询一下 没报名的人全部吊销（吊销改为注销）资格证
     *   同时清除人员的上岗证编号，同时人员状态从复训变改为初训
     * </>
     * @param pvTrainingClass 培训班管理
     * @return 结果
     */
    @Override
    public int updatePvTrainingClass(PvTrainingClass pvTrainingClass) {
        if (pvTrainingClass.getStatus() != null && pvTrainingClass.getStatus().equals(2)){
            List<Cert> certs = certService.selectCertList(Cert.builder().deptId(SecurityUtils.getDeptId()).build());
            ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(certs.size()), new ThreadPoolExecutor.CallerRunsPolicy());
            for (Cert cert : certs) {
                executor.submit(()->{
                    try {
                        Long userId = cert.getStudentId();
                        //查询该学生今年的报名记录
                        PvStudentRecord record = pvStudentRecordService.selectPvStudentRecordThisYear(userId);
                        if (ObjectUtil.isEmpty(record)){
                            //清除上岗证
                            userService.resetPostNumber(userId);
                            certService.resetCertNo(userId);
                            //修改状态为初训
                            infoService.resetReservedOne(userId);
                        }
                    }catch (Exception e){
                        log.error("",e);
                    }
                });
            }
        }
        return pvTrainingClassMapper.updatePvTrainingClass(pvTrainingClass);
    }

    /**
     * 批量删除培训班管理
     *
     * @param ids 需要删除的培训班管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePvTrainingClassByIds(Long[] ids) {
        classScoreMapper.deletePvClassScoreByIds(ids);
        return pvTrainingClassMapper.deletePvTrainingClassByIds(ids);
    }

    /**
     * 删除培训班管理信息
     *
     * @param id 培训班管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deletePvTrainingClassById(Long id) {
        classScoreMapper.deletePvClassScoreById(id);
        return pvTrainingClassMapper.deletePvTrainingClassById(id);
    }

    @Override
    public PvTrainingClass selectPvTrainingYearFirst(Long deptId) {
        PvTrainingClass pvTrainingClass =  PvTrainingClass.builder().reservedOne(deptId).build();
        Map<String, Object> params = new HashMap<>();
        Date date = new Date();
        params.put("beginStartTime", DateUtil.beginOfYear(date).toDateStr());
        params.put("endEndTime", DateUtil.endOfYear(date).toDateStr());
        pvTrainingClass.setParams(params);
        List<PvTrainingClass> pvTrainingClasses = pvTrainingClassMapper.selectPvTrainingClassList(pvTrainingClass);
        return ObjectUtil.isEmpty(pvTrainingClasses) ? null : pvTrainingClasses.get(pvTrainingClasses.size()-1);
    }

    @Override
    public PvTrainingClass selectPvTrainingYearLast(Long deptId) {
        PvTrainingClass pvTrainingClass =  PvTrainingClass.builder().reservedOne(deptId).build();
        Map<String, Object> params = new HashMap<>();
        Date date = new Date();
        params.put("beginStartTime", DateUtil.beginOfYear(date).toDateStr());
        params.put("endEndTime", DateUtil.endOfYear(date).toDateStr());
        pvTrainingClass.setParams(params);
        List<PvTrainingClass> pvTrainingClasses = pvTrainingClassMapper.selectPvTrainingClassList(pvTrainingClass);
        return ObjectUtil.isEmpty(pvTrainingClasses) ? null : pvTrainingClasses.get(0);
    }

    @Override
    public void smsSend(Long id) {
        //查询该培训班下的学生手机号码
        List<SysUser> users = userService.selectUserList(SysUser.builder().userType("2").build());
        //查询培训班信息
        PvTrainingClass clazz = pvTrainingClassMapper.selectPvTrainingClassById(id);
        //创建线程池
        ThreadPoolExecutor executor = ExecutorUtil.customThreadExecutor(4, 4, 0L, users.size());
        //发送短信
        for (SysUser user : users) {
            executor.execute(()->{
                if (StrUtil.isNotBlank(user.getPostsNumber())){
                    String date = DateUtil.formatDate(clazz.getStartTime());
//                    sms.sendReOpenClass(user.getPhonenumber(),user.getNickName(),DateUtil.thisYear(),date,"08:00:00",date);
                }
            });
        }
        //修改状态
        clazz.setReservedTwo(1);
        pvTrainingClassMapper.updatePvTrainingClass(clazz);
    }

    @Override
    public int smsSendPeopleCount() {
        return userService.selectUserCount(SysUser.builder().userType("2").build());
    }
}
